#!/bin/bash

################################################################################
# plan tool for ADA/mcRNC
#
# usage: zplan_new -d -a -u [-f planfile.xml | -i]
#
# author: Limbo
# creat time: 2014-04-01
#
# based on 223a8bc0c8709c947f86053dc57d599d  /opt/nokiasiemens/bin/zplan
#
################################################################################

LOG="/var/log/master-syslog"
UPLOAD_MSG="Plan upload end with"
ACTIVATION_MSG="Plan activation end with"
DOWNLOAD_MSG="Plan download end with"
DATA="xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xdffffffff,xd00,xb44,xb45,xb46,xb41,xb55,xb4c,xb54,xb20,xb45,xb52,xb52,xb4f,xb52,xb20,xb54,xb45,xb58,xb54,xb00,xb00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00,xd00"
TITLE="zplan_new"

function _log()
{
    echo -n "$TITLE: $@"
    if [ $1 = "info" ]; then
        logger -t $TITLE -p6 "$0: $@"
    elif [ $1 = "warn" ]; then
        logger -t $TITLE -p4 "$0: $@"
    else
        logger -t $TITLE -p2 "$0: $@"
    fi
}

function fWaitResponse() {
    echo "Waiting response from rayman"
    regex=$1
    err_code=""
    iserror=0
    errlinenum=0
    tail $LOG -n0 -F -q | while read line; do
    if [[ $line =~ $regex ]]; then
        if [[ -z `echo $line | egrep "error status: 0|Success"` ]]; then
            echo -e "Got following response:  \e[0;31m *** Error ***\e[00m" 
            iserror=1
            echo $line
        else
            echo -e "Got following response:  \e[0;32m Operation succeeded\e[00m"
            echo $line
            echo
            pkill -9 -P $$ tail
            return 0
        fi
    fi
    
    if [ -n "$err_code" -a $iserror -eq 1 ]; then
        echo "trace error: $err_code"
        dxserrcli $err_code | grep -v "^$"
        pkill -9 -P $$ tail
        return 1
    fi
    if [[ $line =~ "err [A-Z]+-0" ]]; then
        err_code_tmp=$(echo "${line##*:}"| grep -o "\w\+" | sed -n '1p')
        if [ "${err_code_tmp:0:2}" == "0x" -a ${#err_code_tmp} -ne 4 ]; then
            err_code=$err_code_tmp
            echo $line
        fi
        if [ $iserror -eq 1 ]; then
            errlinenum=$(expr $errlinenum + 1)
            if [ $errlinenum -gt 2 ]; then
                echo "No error code found."
                pkill -9 -P $$ tail
                return 1
            fi
        fi
    fi
    done
}

function checkServer(){
    local server_ps=$(ps -A | grep "download_stub" | sed "s#^\ \+##g")
    if [ -n "$server_ps" ]; then
        serverPID=$(echo $server_ps | awk '{print $1}')
        kill $serverPID
        wait $serverPID 2>/dev/null
    fi
    
    ### "start message server download_stub"
    cd /opt/nokiasiemens/SS_QNTools/script
    source startstub.sh &
    cd /root
    sleep 1
}

function this_help(){
    echo '[Fucntion] plan tool for ADA/mcRNC.'
    echo "[Useage] $TITLE -d -a -u [-f plan.xml | -i]"
}

### Main
download_plan=0
active_plan=0
upload_plan=0
plan_file=''
ignore_file=0

if [ $# -eq 0 ];then
  this_help
  exit
fi
while [ $# -gt 0 ]; do
  case $1 in
    -h)
      this_help
      exit
      ;;
    -d)
      # action download
      download_plan=1
      shift
      ;;
    -a)
      # action upload plan
      active_plan=1
      shift
      ;;
    -u)
      # upload upload plan 
      upload_plan=1
      shift
      ;;
    -i)
      ignore_file=1
      shift
      ;;
    -f)
      plan_file=$(readlink -f "$2")
      shift
      shift
      ;;
    *)
      shift
      ;;
  esac
done

if [ $ignore_file -eq 0 -a $download_plan -eq 1 ]; then
    if [ -z "$plan_file" ]; then
        echo -e "\e[0;31m *** Error ***\e[00m\nNo plan for download."
        exit 1
    fi
    if [ ! -f "$plan_file" ]; then
        echo -e "\e[0;31m *** Error ***\e[00m\nPlan file ($plan_file) is not exist."
        exit 1
    fi
    cp "$plan_file" "/mnt/$(ls /mnt | grep 'OMU')/plan/RNWPLAND.XML"
fi
if [ $download_plan -eq 0 -a $active_plan -eq 0 -a $upload_plan -eq 0 ]; then
    echo -e "\e[0;31m *** Error ***\e[00m\nNo action for plan."
    echo
    this_help
    exit 1
fi

ADDRS=(`ilclifunit -u | grep -i omu | grep $HOSTNAME | awk '{print $2,$3}'`)
export LIBGEN_USE_PHYS_ADDR=${ADDRS[1]}
export LIBGEN_USE_LOG_ADDR=${ADDRS[0]}
export GET_CONFIG=/etc/LibgenConfig_OMU.ini
export UNIT_NAME=OMU

if [ "$HW_PLATFORM" == "BCN" ]; then  # mcRNC
    FAM="QNRAYMAN"
    if [ `fshascli -s -R /CFPU-0/QNO* | grep role | grep -c ACTIVE` -eq 0 ]; then
        echo -e "\e[0;31mError:\e[00m QNOMUServer should be active under @CFPU-0"
        exit 1
    fi
else  # ADA
    FAM="QFRAYMAN"
fi

#Set app-log rule zplan with notice level
fsclish -c "add troubleshooting app-log rule rule-id zplanrnwdb keep family-name $FAM level notice" &> /dev/null

#Delete the app-log rule id zplan in case of CTRL-C
trap "fsclish -c \"delete troubleshooting app-log rule rule-id zplanrnwdb\" &&  kill -9 -$$; exit" SIGINT SIGTERM

checkServer

continue_flag=1

### PLAN DOWNLOAD PROCEDURE
if [ $continue_flag -eq 1 -a $download_plan -eq 1 ]; then
    _log info "download started"
    dmxsend -- -h *,7002,777,0,0,0,0,6034 -b xb1,xb0
    fWaitResponse "$DOWNLOAD_MSG"
    if [ $? -eq 1 ]; then
        continue_flag=0
    fi
fi

if [ $continue_flag -eq 1 -a $download_plan -eq 1 -a $active_plan -eq 1 ]; then
    sleep 1
fi

### PLAND ACTIVATION PROCEDURE
if [ $continue_flag -eq 1 -a $active_plan -eq 1 ]; then
    _log info "activation started"
    dmxsend -- -h *,7002,777,0,0,0,0,6034 -b xb2,xb0
    fWaitResponse "$ACTIVATION_MSG"
    if [ $? -eq 1 ]; then
        continue_flag=0
    fi
fi

if [ $continue_flag -eq 1 -a $active_plan -eq 1 -a $upload_plan -eq 1 ]; then
    sleep 1
fi

### PLAND UPLOAD PROCEDURE
if [ $continue_flag -eq 1 -a $upload_plan -eq 1 ]; then
    _log info "upload started"
    dmxsend -- -h *,7002,777,0,0,0,0,6034 -b xb3,xb0
    fWaitResponse "$UPLOAD_MSG"
    if [ $? -eq 1 ]; then
        continue_flag=0
    else
        gunzip "/mnt/$(ls /mnt | grep 'OMU')/plan/RNWPLANU.XML.gz"
    fi
fi

fsclish -c "delete troubleshooting app-log rule rule-id zplanrnwdb" > /dev/null

### "Sending upload end (rnw_plan_upload_end_s) message:"
dmxsend -- -h *,7002,0523,0001,00,00,0000,d7f5 -b $DATA > /dev/null

pkill download_stub

